package com.tuocent.dagv2.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tuocent.dagv2.common.AjaxResult;
import com.tuocent.dagv2.constant.Constants;
import com.tuocent.dagv2.constant.PublicConst;
import com.tuocent.dagv2.entity.Projects;
import com.tuocent.dagv2.mapper.ProjectsMapper;
import com.tuocent.dagv2.service.IProjectsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import org.springframework.util.DigestUtils;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 项目信息 服务实现类
 * </p>
 *
 * @author Vincent
 * @since 2025-07-22
 */
@Service
public class ProjectsServiceImpl extends ServiceImpl<ProjectsMapper, Projects> implements IProjectsService {

    @Override
    public String projectInfo(Model model) {
        return "/project/projectInfo";
    }

    @Override
    public AjaxResult getProjectInfo(Integer page, Integer limit) {
        Page<Projects> data = page(new Page<>(page, limit));
        return AjaxResult.success(data.getRecords(), data.getTotal());
    }

    @Override
    public AjaxResult importProject(MultipartFile file) throws FileNotFoundException {
        File dir = new File(ResourceUtils.getURL("").getPath() + "/Upload/files/");
        if (!dir.exists()) {
            try {
                dir.mkdirs();
            } catch (Exception e) {
                return AjaxResult.error("创建文件目录失败。错误信息：" + e);
            }
        }
        String fileName = file.getOriginalFilename();
        File dest = new File(dir.getPath() + "/" + fileName);
        try {
            file.transferTo(dest);
            // 时区
            ZoneId zone = ZoneId.systemDefault();

            byte[] bytes = Files.readAllBytes(Paths.get(dest.getPath()));
            JSONObject jsonObject = JSONObject.parseObject(new String(bytes, StandardCharsets.UTF_8));
            String id = jsonObject.containsKey("id") ? jsonObject.getString("id") : "";
            String code = jsonObject.containsKey("code") ? jsonObject.getString("code") : "";
            String contractNo = jsonObject.containsKey("contractNo") ? jsonObject.getString("contractNo") : "";
            String project = jsonObject.containsKey("project") ? jsonObject.getString("project") : "";
            String pm = jsonObject.containsKey("pm") ? jsonObject.getString("pm") : "";
            String clientCode = jsonObject.containsKey("clientCode") ? jsonObject.getString("clientCode") : "";
            String client = jsonObject.containsKey("client") ? jsonObject.getString("client") : "";
            String remark = jsonObject.containsKey("remark") ? jsonObject.getString("remark") : "";
            String sign = jsonObject.containsKey("sign") ? jsonObject.getString("sign") : "";
            LocalDate psStartDate = jsonObject.containsKey("psStartDate") ? Instant.ofEpochMilli(jsonObject.getLong("psStartDate")).atZone(zone).toLocalDate() : null;
            LocalDate psEndDate = jsonObject.containsKey("psEndDate") ? Instant.ofEpochMilli(jsonObject.getLong("psEndDate")).atZone(zone).toLocalDate() : null;
            String signStr = id + project + pm;
            String md5Sign = DigestUtils.md5DigestAsHex(signStr.getBytes(StandardCharsets.UTF_8)).toUpperCase() + Constants.PM_CHECK_CODE;
            md5Sign = DigestUtils.md5DigestAsHex(md5Sign.getBytes(StandardCharsets.UTF_8)).toUpperCase();
            if ("".equals(sign) || !sign.equals(md5Sign)) {
                return AjaxResult.error("该文件不是正确的项目文件");
            }

            Projects data = getById(id);
            if (data == null) {
                data = new Projects();
                data.setId(id);
            }
            data.setCode(code);
            data.setName(project);
            data.setContractNo(contractNo);
            data.setProjectLeader(pm);
            data.setClientName(client);
            data.setRemark(remark);
            data.setStatus("0");
            data.setIsStart("0");
            data.setIsDel("0");
            data.setPsStartDate(psStartDate);
            data.setPsEndDate(psEndDate);
            data.setClientCode(clientCode);
            return saveOrUpdate(data) ? AjaxResult.success("项目文件导入成功") : AjaxResult.error("项目文件导入失败");
        } catch (Exception e) {
            return AjaxResult.error("项目文件导入失败。错误信息：" + e.getMessage());
        }
    }

    @Override
    public AjaxResult delProject(Map<String, Object> data) {
        String id = data.containsKey("id") ? data.get("id").toString() : "";
        Projects project = getById(id);
        if (project == null) {
            return AjaxResult.error("没有可删除的项目");
        }
        if (!"0".equals(project.getIsStart())) {
            return AjaxResult.error("该项目不在可删除的状态");
        }
        try {
            return removeById(id) ? AjaxResult.success("删除项目成功") : AjaxResult.error("删除项目失败");
        } catch (Exception e) {
            return AjaxResult.error("删除项目信息失败。错误信息：" + e.getMessage());
        }
    }

    @Override
    public String setProjectStart(Model model, String id) {
        model.addAttribute("id", id);
        model.addAttribute("sdate", LocalDate.now());
        return "/project/setProjectStart";
    }

    @Override
    public AjaxResult projectStart(Map<String, Object> data) {
        String id = data.containsKey("id") ? data.get("id").toString() : "";
        LocalDate startDate = data.containsKey("startDate") ? LocalDate.parse(data.get("startDate").toString(), PublicConst.dateFormat) : LocalDate.now();
        Projects project = getById(id);
        if (project == null) {
            return AjaxResult.error("没有需要启动的项目");
        }
        if (!"0".equals(project.getStatus()) && !"1".equals(project.getStatus())) {
            return AjaxResult.error("该项目不在可启动状态");
        }
        project.setStatus("1");
        project.setIsStart("1");
        project.setStartDate(startDate);
        return updateById(project) ? AjaxResult.success("项目启动成功") : AjaxResult.error("项目启动失败");
    }

    @Override
    public AjaxResult projectFinish(Map<String, Object> data) {
        String id = data.containsKey("id") ? data.get("id").toString() : "";
        LocalDate endDate = data.containsKey("endDate") ? LocalDate.parse(data.get("endDate").toString(), PublicConst.dateFormat) : LocalDate.now();
        Projects project = getById(id);
        if (project == null) {
            return AjaxResult.error("没有需要结束的项目");
        }
        if (!"1".equals(project.getStatus())) {
            return AjaxResult.error("该项目不在可结束的状态");
        }
        if (endDate.isBefore(project.getStartDate())) {
            return AjaxResult.error("项目完成日期不可小于项目启动日期");
        }
        project.setStatus("2");
        project.setEndDate(endDate);
        return updateById(project) ? AjaxResult.success("项目成功设置为结束") : AjaxResult.error("项目设置为结束失败");
    }

    @Override
    public String setProjectFinish(Model model, String id) {
        model.addAttribute("id", id);
        model.addAttribute("endDate", LocalDate.now());
        return "/project/setProjectFinish";
    }

    @Override
    public AjaxResult getAllProjectInfo() {
        List<Projects> projects = list(new QueryWrapper<Projects>().eq("is_del", "0"));
        return AjaxResult.success(projects);
    }
}
